package org.zoomdev.zoom.aop.utils;

import org.zoomdev.zoom.aop.factory.impl.AsmClassloader;
import org.zoomdev.zoom.common.exceptions.ZoomException;

public class AopUtils {
    public static final String TAIL = "$Enhance";


    public static String getEnhancedClassName(Class<?> type) {
        return type.getName() + TAIL;
    }

    public static String getEnhancedClassName(String type) {
        return type + TAIL;
    }


    /**
     * 方法hash
     *
     * @param declaringClass
     * @param method
     * @return
     */
    public static int calculateMethodHash(Class<?> declaringClass, java.lang.reflect.Method method) {

        Class orgClass = getOriginalClass(declaringClass);
        String name = method.getName();
        if (name.startsWith("__")) {
            name = name.substring(2);
        }

        // 使用稳定的方法签名计算哈希值
        String signature = orgClass + "#" + name + "(";

        Class<?>[] paramTypes = method.getParameterTypes();
        for (int i = 0; i < paramTypes.length; i++) {
            if (i > 0) signature += ",";
            signature += paramTypes[i].getName();
        }
        signature += "):" + method.getReturnType().getName();

        // 使用Java内置的哈希算法，确保跨JVM一致性
        return signature.hashCode();
    }


    /**
     * 获取未增强之前的类
     *
     * @param type
     * @param classLoader
     * @return
     */
    public static Class<?> getOriginalClass(Class<?> type) {
        if (type.getSimpleName().endsWith(TAIL)) {
            try {
                String className = type.getName();
                className = className.substring(0, className.length() - 8);
                type = Class.forName(className, false, AsmClassloader.get());
            } catch (ClassNotFoundException e) {
                throw new ZoomException(e);
            }
        }
        return type;
    }
}
